<template>
  <div>
    <!-- 2.6使用status渲染 -->
    <el-dialog
      :title="status.isAdd ? '分类添加' : '分类编辑'"
      :visible.sync="status.isshow"
      @closed="closed"
    >
      <!-- 6.4 绑定数据到表单 -->
      <el-form :model="form">
        {{ form }}
        <el-form-item label="上级分类" label-width="120px">
          <el-select v-model="form.pid" placeholder="请选择上级分类">
            <el-option label="顶级分类" :value="0"></el-option>
            <!-- 循环 -->
            <el-option
              v-for="item in list"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" label-width="120px">
          <el-input v-model="form.catename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="120px">
          <!-- 2.2自己的图  :画图--》修改文件得到文件对象 -->
          <!--2.4.2 清空数据的时候，form可以清空，图片地址也可以清空，但是input上的文件清空不了。所以将input条件渲染。
            弹框出现，新建一个input,这样，之前的input的选择不会影响新一次input的选择 -->
          <div class="my-upload">
            <h3 class="my-upload-plus">+</h3>
            <img v-if="imgUrl" class="my-upload-img" :src="imgUrl" alt="" />
            <input
              v-if="status.isshow"
              type="file"
              class="my-upload-input"
              @change="changeFile"
            />
          </div>

          <!-- element-ui 文件上传 -->
          <!-- <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-change="changeFile2"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload> -->
        </el-form-item>

        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" v-if="status.isAdd" @click="add"
          >添 加</el-button
        >
        <el-button type="primary" v-else @click="update">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
/* 1.静态页
   2.添加
       2.1 初始化form 绑定到页面
       2.2 图  (1.自己的上传；2.element-ui上传)
       2.3 添加
  3.混入
  4.列表  vuex
      4.1状态层定了数据和方法以及逻辑
      4.2 list.vue 发请求，取出来数据，展示
      4.3 form.vue 上级分类也要用到列表数据；添加成功调用vuex的reqList
  5.编辑
  6.修改
  7.删除组件的封装

*/
import {
  reqcateadd,
  reqcateedit,
  reqcateinfo,
} from "../../../http/api";
import { errorAlert, successAlert } from "../../../utils/alert";
import { mapGetters, mapActions } from "vuex";
import path from "path";
export default {
  components: {},
  props: ["status"],
  data() {
    return {
      // 2.1 初始化form 绑定到页面
      form: {
        pid: "",
        catename: "",
        img: "",
        status: 1,
      },
      // 图片地址
      imgUrl: "",
    };
  },
  computed: {
    ...mapGetters({
      list: "cate/list",
    }),
  },
  mounted() {},
  methods: {
    ...mapActions({
      reqList: "cate/reqList",
    }),

    //获取文件
    changeFile(e) {
      //得到文件
      let file = e.target.files[0];

      //判断大小 1M=1024KB 1KB=1024B   file.size B
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件大小最大2M");
        return;
      }
      // 判断文件类型 file name: "2.2.2.2.2.jpeg"
      let imgArr = [".jpg", ".jpeg", ".gif", ".png"];

      // let houzhui=file.name.slice(file.name.lastIndexOf("."))
      // console.log(houzhui);
      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }

      // 根据文件生成一个图片地址，赋值给imgUrl
      this.imgUrl = URL.createObjectURL(file);
      //将文件存到form.img
      this.form.img = file;
    },

    //element-ui 上传文件处理
    changeFile2(e) {
      let file = e.raw; //文件

      //判断大小 1M=1024KB 1KB=1024B   file.size B
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件大小最大2M");
        return;
      }
      // 判断文件类型 file name: "2.2.2.2.2.jpeg"
      let imgArr = [".jpg", ".jpeg", ".gif", ".png"];
      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }

      // 根据文件生成一个图片地址，赋值给imgUrl
      this.imgUrl = URL.createObjectURL(file);
      //将文件存到form.img
      this.form.img = file;
    },

    //2.7点了取消
    cancel() {
      this.status.isshow = false;
    },
    //2.4 清空
    empty() {
      this.form = {
        pid: "",
        catename: "",
        img: "",
        status: 1,
      };
      //2.4.1图片单独处理
      this.imgUrl = "";
    },
    // 2.3添加
    add() {
      reqcateadd(this.form).then((res) => {
        if (res.data.code === 200) {
          // 弹成功
          successAlert(res.data.msg);
          // 数据清空
          this.empty();
          // 弹框消失
          this.status.isshow = false;
          // 列表刷新----------此处调用vuex的方法------------------
          this.reqList();
        }
      });
    },

    //7.3点击了编辑按钮 ，获取一条数据
    getOne(id) {
      reqcateinfo({
        id: id,
      }).then((res) => {
        if (res.data.code === 200) {
          /*
            catename: "22"
            img: "/uploads/category/567e3170-3d0e-11ec-b2e3-eb7ca6828ac7.jpeg"
            pid: 0
            status: 1
          */
          this.form = res.data.list;
          //  补id
          this.form.id = id;
          //给图片赋值
          this.imgUrl = this.$pre + this.form.img;
        }
      });
    },
    //8.1修改逻辑
    update() {
      reqcateedit(this.form).then(res=>{
        if(res.data.code==200){
          successAlert(res.data.msg)
          this.empty()
          this.status.isshow=false;
          this.reqList()
        }
      })
    },
    // 9.弹框关闭
    closed() {
      // 如果是添加的取消，什么都不做；如果是编辑的取消，form清空
      if (!this.status.isAdd) {
        this.empty();
      }
    },
  },

  watch: {},
};
</script>
<style scoped lang="less">
@import "../../../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed @primary;
  position: relative;
}
.my-upload-plus {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
}
.my-upload-input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  opacity: 0;
}
.my-upload-img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

// element-ui
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #b39a9a !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

